import React,{useState}from 'react'
import { Button, Form, Input, message } from 'antd';
import {useNavigate } from 'react-router-dom'
import { UserOutlined, LockOutlined,WomanOutlined } from '@ant-design/icons';
import cookie from 'react-cookies'
import { day, hour, getRemainTime } from '@/assets/data/common.js'
import logoImg from '@/assets/img/logo.png'
import '@/assets/less/login.less'
import { loginApi, errLoginApi, restoreCountApi, userLoginInfoApi } from '@/request/index'
import { addUserLoginApi } from '@/request/logmanagment.js'

function Login() {
  const [load, setLoad] = useState(false)
  const navigate = useNavigate()
  const [getCodeImg, setCodeImg] = useState("http://localhost:3000/api/getcode") //验证码图片
  
  /* 更新验证码 */
  const changeCode=(event)=>{
    event.preventDefault() //阻止默认事件
    event.target.setAttribute("src", getCodeImg +"?"+Math.random());
  }
    

  /* 登陆 */
  var allowedToLogin=true  //判断是否允许登陆
  const onFinish = (value) => {
    setLoad(true)
    let loginInfo={
      username:value.username,
      password:value.password,
      code:value.code
    }
    const preventLogin = localStorage.getItem(`${loginInfo.username}_preventLoginTime`) || ""
    if (preventLogin!=="") { 
      setLoad(false)                                                    //限制登陆
      let remainTime = JSON.parse(preventLogin)
      let time = new Date().getTime()
      message.warn(`当前密码错误次数已达上限,剩余时间为：${getRemainTime(remainTime.date)}`)
      allowedToLogin = time - parseInt(preventLogin) > 0                         //判断限制登陆时间是否超过24小时
      if(allowedToLogin){    
        setLoad(true)    
        localStorage.setItem("firstErrTime", time)
        localStorage.removeItem("nextErrTime")
        localStorage.removeItem(`${loginInfo.username}_preventLoginTime`)
        userLogin(loginInfo)
      }
    }else{
      userLogin(loginInfo)
    }

  }
  
  const userLogin = (loginInfo) => {
    /* 日志参数 */
    let logParmas={
      id:'',
      username:"",
      function_module:"登陆模块",
      search_condation:"",
      handle:"登陆"
    }
    loginApi(loginInfo).then(res => {
      let code = res.code
      if (code === 0) {
        message.error(res.message);
        setLoad(false)
      } else if (code === 1) {
        //计算错误登陆
        getErrCount(loginInfo.username)
        getUserLoginLog({ ...logParmas, id: "", username: loginInfo.username })    //登陆失败日志
        setLoad(false)
      } else {
        let userInfo = res.data[0]
        let expires = new Date(day); //1天
        cookie.save('userInfo', userInfo, { path: '/', expires })   //存储用户信息cookie,{ path: ‘/’ } 表式cookie可以被所有页面访问到。      
        setTimeout(() => {
          setLoad(false)
        }, 2000);
        navigate("/home")
        restoreCountApi(loginInfo.username)
        getUserLoginLog({ ...logParmas, id: userInfo.id, username: userInfo.username }) //登陆成功日志
        userLoginInfoApi(userInfo.id,userInfo.ip).then(res=>{})
        localStorage.setItem("firstErrTime", new Date().getTime())
      }
    })

  }

  /* 获取用户登陆日志 */
  const getUserLoginLog = (data)=>{
    addUserLoginApi(data).then(res=>{})
  }

  /* 计算登陆错误次数 */
  const getErrCount = (username)=>{
    errLoginApi(username).then(res=>{
      if(res.count === 6){
        localStorage.setItem("firstErrTime", new Date().getTime())       // 存储第一次失败的时间
        message.error(res.message)
      }else{
        localStorage.setItem("nextErrTime", new Date().getTime())        // 存储下一次失败的时间
        let firstErrTime = parseInt(localStorage.getItem("firstErrTime"))
        let lastErrTime = parseInt(localStorage.getItem("nextErrTime"))
        let useTime = Math.floor((lastErrTime - firstErrTime)/1000)      //计算任何从第二次之后的每一次与第一次错误的时间差

        if( res.count===0 && useTime<=hour){                               //在一小时内超过六次
          localStorage.setItem(`${username}_preventLoginTime`, JSON.stringify({ "name": username, "date": day }))                  //超过次数，24小时禁止登陆
          message.error(res.message)
        } else if (useTime > hour){                                       //六次之内，任意一次与第一次间隔超过一小时，恢复错误次数
          localStorage.setItem("firstErrTime", new Date().getTime())
          restoreCountApi(username).then(res=>{
            message.error(res.message)
          })
        }else{
          message.error(res.message)
        }
      }
     
    })  
  }
  return (
  <div className="login">
    <div className='login_box'>
      <img src={logoImg} alt="" /><span className='title'>数据分析系统</span>
      <div className='login_content'>
        <Form name="basic" initialValues={{
                remember: true,
              }} onFinish={onFinish} autoComplete="off">
          <Form.Item name="username" rules={[ { required: true, message: '请输入用户名！' , }, ]}
            style={{ backgroundColor: 'transparent' }}>

            <Input className='login-input' size="large" style={{ backgroundColor: 'transparent', border: "none" }}
              prefix={<UserOutlined style={{ color: "#fff" }} />} placeholder="请输入用户名" />
          </Form.Item>

          <Form.Item name="password" rules={[ { required: true, message: '请输入密码！' , }, ]}>
            <Input.Password className='login-input' style={{ backgroundColor: 'transparent', border: "none" }}
              size="large" prefix={<LockOutlined style={{ color: "#fff" }} />} placeholder="请输入密码" />
          </Form.Item>

          <Form.Item name="code" rules={[ { required: true, message: '请输入验证码！' , }, ]}>
            <Input className='login-input' style={{ backgroundColor: 'transparent', border: "none" }} size="large"
              prefix={<WomanOutlined style={{ color: "#fff" }} />} placeholder="请输入验证码" />
          </Form.Item>
          <img src={getCodeImg} className='codeImg' onClick={changeCode} title="点击更换" />
          <Form.Item>
            <Button size='large' type="primary" htmlType="submit" style={{marginLeft:"20px"}} loading={load}>登录</Button>
            <p className="toregister">没有账号？<a href="/register">点击前往注册</a></p>
          </Form.Item>
        </Form>
      </div>
    </div>
  </div>
  )
}
export default Login